package com.mmp.main.servlet.joborder;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.bo.Message;
import com.mmp.common.util.Common;
import com.mmp.common.util.FileUtil;
import com.mmp.main.entity.JobOrder;
import com.mmp.main.entity.JobOrderSparePart;
import com.mmp.main.entity.SpInventoryContent;
import com.mmp.main.entity.SpInventoryTransaction;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

/**
 * Servlet implementation class JobOrderFollowupSecondPhaseProcessServlet
 */
@MultipartConfig
public class JobOrderFollowupSecondPhaseProcessServlet extends JobOrderTrackingProcessServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		if (!skipActionProcessing(request)) {

			int jobOrderId = WebUtil.getParamValueAsInteger(request, "jobOrderId", 0);

			JobOrder order = dbQueryManager.findById(jobOrderId, JobOrder.class);

			resetProperties(order);

			String[] joRequestFormUrl = FileUtil.uploadFiles(request, "joRequestFormUrl");
			// if (joRequestFormUrl != null && joRequestFormUrl.length != 0)
			order.setRequestFormUrl(Common.concatenateValues(joRequestFormUrl));

			order.setFixIncludingSpareParts(("1").equals(request.getParameter("fixIncludingSpareParts")) ? true : false);

			if (!order.getFixIncludingSpareParts()) {
				setFinalActionDetails(order, request);

			} else {

				Integer spSource = WebUtil.getParamValueAsInteger(request, "spSource", null);
				order.setSpSource(spSource);

				if (spSource == Enums.JOBORDER_SP_SOURCES.INVENTORY.getId()) {
					try {
						order.setInventoryTransactionDate(WebUtil.getParamValueAsDate(request, "spTransDate", null));
						setSparePartsFromSpInventory(request, order);
						setFinalActionDetails(order, request);
					} catch (Exception e) {
						announceErorrMessage(request, response, "أحد كميات قطع الغيار المطلوبة غير متاحة");
						return;
					}

				} else if (spSource == Enums.JOBORDER_SP_SOURCES.PURCHASE_ORDER.getId()) {
					String[] spPoScanUrl = FileUtil.uploadFiles(request, "spPoScanUrl");
					// if (spPoScanUrl != null && spPoScanUrl.length != 0)
					order.setSpPoScanUrl(Common.concatenateValues(spPoScanUrl));
					setSparePartsOfPurchaseOrder(request, order);
					setFinalActionDetails(order, request);

				} else if (spSource == Enums.JOBORDER_SP_SOURCES.AGENT.getId()) {

					String[] agentReportUrl = FileUtil.uploadFiles(request, "agentReportUrl");

					if (agentReportUrl != null && agentReportUrl.length != 0) {
						order.setAgentReportUrl(Common.concatenateValues(agentReportUrl));
						order.setLastCompletedPhaseId(Enums.JOBORDER_FOLLOWUP_PHASES.AGENT_REPORT_UPLOADED.getId());
					}

					if (request.getParameter("quotationRecieved") != null) {
						order.setQuotationRecieved(true);
						String[] quotationScanUrl = FileUtil.uploadFiles(request, "quotationScanUrl");
						order.setQuotationScanUrl(Common.concatenateValues(quotationScanUrl));
						order.setQuotationDate(WebUtil.getParamValueAsDate(request, "quotationDate", null));
						order.setQuotationExpireDate(WebUtil.getParamValueAsDate(request, "quotationExpireDate", null));
						setSparePartsInsideQuotation(request, order);
						order.setSecondAction(WebUtil.getParamValue(request, "secondAction", null));
						order.setSecondActionDate(WebUtil.getParamValueAsDate(request, "secondActionDate", null));
						order.setLastCompletedPhaseId(Enums.JOBORDER_FOLLOWUP_PHASES.QUOTATION_RECIEVED.getId());
					}

					if (WebUtil.userHasRightToAcceptSparePartsQuotation(request)
							&& request.getParameter("quotationAccepted") != null) {
						order.setQuotationAccepted(true);
						order.setQuotationAcceptanceNo(WebUtil.getParamValue(request, "quotationAcceptanceNo", null));
						order.setQuotationAcceptanceDate(WebUtil.getParamValueAsDate(request,
								"quotationAcceptanceDate", null));
						order.setLastCompletedPhaseId(Enums.JOBORDER_FOLLOWUP_PHASES.SECOND_ACTION_TAKEN.getId());
					}

				}
			}

			dbQueryManager.mergeEntity(order);

			if (request.getParameter("showJobOrderReport") == null)
				setMessage(request, new Message("تم الحفظ بنجاح", Message.MESSAGE_TYPE.SUCCESS));
		}

		updateNotificationsThenGoForward(request, response);

	}

	private void resetProperties(JobOrder order) {

		if (order.getJobOrderSpareParts() == null)
			order.setJobOrderSpareParts(new ArrayList<JobOrderSparePart>());
		else
			order.getJobOrderSpareParts().clear();

		if (order.getSparePartsInsideQuotation() == null)
			order.setSparePartsInsideQuotation(new ArrayList<JobOrderSparePart>());
		else
			order.getSparePartsInsideQuotation().clear();

		// if (order.getSparePartsOutsideQuotation() == null)
		// order.setSparePartsOutsideQuotation(new
		// ArrayList<JobOrderSparePart>());
		// else
		// order.getSparePartsOutsideQuotation().clear();

		order.setSpSource(null);

		order.setInventoryTransactionDate(null);

		order.setSpPoScanUrl(null);

		/*
		 * order.setFinalAction(null); order.setFinalActionDate(null);
		 * order.setFinalReportUrl(null); order.setFinalAgentReportUrl(null);
		 */

		order.setAgentReportUrl(null);

		order.setQuotationRecieved(null);
		order.setQuotationScanUrl(null);
		order.setQuotationDate(null);
		order.setQuotationExpireDate(null);

		order.setQuotationAccepted(null);
		order.setQuotationAcceptanceDate(null);

		order.setSecondAction(null);
		order.setSecondActionDate(null);

	}

	private void setSparePartsInsideQuotation(HttpServletRequest request, JobOrder order) throws FileNotFoundException,
			IOException, ServletException {

		String jobOrderSpareParts_rowOrder = request.getParameter("agentSpareParts_rowOrder");
		if (jobOrderSpareParts_rowOrder != null && !jobOrderSpareParts_rowOrder.isEmpty()) {
			String[] indexes = jobOrderSpareParts_rowOrder.split(",");
			int quantity = 0;
			float price = 0;
			for (int i = 0; i < indexes.length; i++) {
				JobOrderSparePart sPart = new JobOrderSparePart();
				quantity = WebUtil.getParamValueAsInteger(request, "agentSpareParts_accQuantity_" + indexes[i], 0);
				price = WebUtil.getParamValueAsFloat(request, "agentSpareParts_accPrice_" + indexes[i], 0f);

				sPart.setInQuotation(true);
				sPart.setQuantity(quantity);
				sPart.setPrice(price);
				sPart.setTotalPrice(quantity * price);
				sPart.setDescription(WebUtil.getParamValue(request, "agentSpareParts_accDescription_" + indexes[i],
						null));
				order.addSparePartsInsideQuotation(sPart);
			}
		}
	}

	private void setSparePartsOfPurchaseOrder(HttpServletRequest request, JobOrder order) throws FileNotFoundException,
			IOException, ServletException {

		String jobOrderSpareParts_rowOrder = request.getParameter("poSpareParts_rowOrder");
		if (jobOrderSpareParts_rowOrder != null && !jobOrderSpareParts_rowOrder.isEmpty()) {
			String[] indexes = jobOrderSpareParts_rowOrder.split(",");
			int quantity = 0;
			float price = 0;
			for (int i = 0; i < indexes.length; i++) {
				JobOrderSparePart sPart = new JobOrderSparePart();
				quantity = WebUtil.getParamValueAsInteger(request, "poSpareParts_accQuantity_" + indexes[i], 0);
				price = WebUtil.getParamValueAsFloat(request, "poSpareParts_accPrice_" + indexes[i], 0f);

				sPart.setQuantity(quantity);
				sPart.setPrice(price);
				sPart.setTotalPrice(quantity * price);
				sPart.setDescription(WebUtil.getParamValue(request, "poSpareParts_accDescription_" + indexes[i], null));
				order.addJobOrderSparePart(sPart);
			}
		}
	}

	private void setSparePartsFromSpInventory(HttpServletRequest request, JobOrder order) throws Exception {

		String jobOrderSpareParts_rowOrder = request.getParameter("inventorySpareParts_rowOrder");
		if (jobOrderSpareParts_rowOrder != null && !jobOrderSpareParts_rowOrder.isEmpty()) {
			String[] indexes = jobOrderSpareParts_rowOrder.split(",");
			int quantity = 0;
			for (int i = 0; i < indexes.length; i++) {

				SpInventoryContent spInventoryContent = dbQueryManager.getSpInventoryContentWithStats(
						getSessionSiteId(request),
						WebUtil.getParamValue(request, "inventorySpareParts_spCode_" + indexes[i], null));

				quantity = WebUtil.getParamValueAsInteger(request, "inventorySpareParts_spQuantity_" + indexes[i], 0);

				if (quantity > spInventoryContent.getAvailableQuantity())
					throw new Exception("الكمية المطلوبة غير متاحة بالمستودع");
				// job order spare parts
				JobOrderSparePart sPart = new JobOrderSparePart();
				sPart.setQuantity(quantity);
				sPart.setPrice(spInventoryContent.getAvgUnitPrice());
				sPart.setTotalPrice(quantity * spInventoryContent.getAvgUnitPrice());
				sPart.setDescription(spInventoryContent.getName());
				sPart.setFromInventory(true);
				sPart.setSpInventoryCategoryId(spInventoryContent);
				order.addJobOrderSparePart(sPart);

				if (WebUtil.userHasRightToCloseJobOrder(request) && request.getParameter("closed") != null) {
					// sp inventory transaction
					SpInventoryTransaction transaction = new SpInventoryTransaction();
					transaction.setSite(spInventoryContent.getSite());
					transaction.setSpInventoryContent(spInventoryContent);
					transaction.setJobOrder(order);
					transaction.setInput(false);
					transaction.setQuantity(quantity);
					transaction.setUnitPrice(spInventoryContent.getAvgUnitPrice());
					transaction.setPerformedBy(getSessionUser(request));
					transaction.setPerformedIn(new Date());
					dbQueryManager.mergeEntity(transaction);

					// sp inventory content
					spInventoryContent.setAvailableQuantity(spInventoryContent.getAvailableQuantity() - quantity);
					spInventoryContent.setLastModefiedBy(getSessionUser(request));
					spInventoryContent.setLastModefiedIn(new Date());
					dbQueryManager.mergeEntity(spInventoryContent);
				}

			}

		}

	}

}
